// 1. 插件类：统一管理所有MethodChannel逻辑
import Flutter
import UIKit
import AliyunPlayer // 引入阿里云播放器SDK

/// 统一管理所有MethodChannel的插件类（包含屏幕保护、阿里云配置、设备UUID）
class CoustomFlutterPlugin: NSObject, FlutterPlugin {
    // 截屏监听者（全局唯一，避免重复注册）
    private var screenCaptureObserver: NSObjectProtocol?
    
    static func register(with registrar: FlutterPluginRegistrar) {
        let instance = CoustomFlutterPlugin()
        
        // 1. 阿里云环境配置通道
        let aliyunChannel = FlutterMethodChannel(
            name: "alivc_environment",
            binaryMessenger: registrar.messenger()
        )
        registrar.addMethodCallDelegate(instance, channel: aliyunChannel)
        
        // 2. 设备UUID及原生方法通道
        let deviceChannel = FlutterMethodChannel(
            name: "com.example.flutter_ios_channel/method",
            binaryMessenger: registrar.messenger()
        )
        registrar.addMethodCallDelegate(instance, channel: deviceChannel)
        

    }
    
    func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        // 阿里云环境配置
        case "setGlobalEnvironment":
            handleAliyunEnvironment(call: call, result: result)
            
        // 设备UUID（通道2）
        case "getDeviceUUID":
            let deviceUUID = KeyChainForUUID.getDeviceUUID()
            result(deviceUUID)
        // 未实现的方法
        default:
            result(FlutterMethodNotImplemented)
        }
    }
}

// MARK: - 私有方法拆分（按功能模块）
private extension CoustomFlutterPlugin {
    /// 处理阿里云环境配置
    func handleAliyunEnvironment(call: FlutterMethodCall, result: @escaping FlutterResult) {
        guard let args = call.arguments as? [String: Any],
              let environment = args["environment"] as? String else {
            result(FlutterError(code: "INVALID_ARG", message: "参数错误，需提供environment", details: nil))
            return
        }
        switch environment {
        case "sea":
            AlivcEnv.getInstance().setGlobalEnvironment(.SEA)
        case "cn":
            AlivcEnv.getInstance().setGlobalEnvironment(.DEFAULT)
        default:
            result(FlutterError(code: "INVALID_ENV", message: "不支持的环境类型", details: nil))
            return
        }
        result(nil)
    }
    
    /// 用于防录屏的安全视图（录制时黑屏）
    private static var secureField: UITextField?

    /// 处理开启屏幕保护
    func handleEnableScreenProtection(result: @escaping FlutterResult) {
        // 1. 移除旧监听
        if let observer = screenCaptureObserver {
            NotificationCenter.default.removeObserver(observer)
        }

        // 2. 监听截屏行为（仅提示，不阻止）
        screenCaptureObserver = NotificationCenter.default.addObserver(
            forName: UIApplication.userDidTakeScreenshotNotification,
            object: nil,
            queue: OperationQueue.main
        ) { [weak self] _ in
            guard let self = self else { return }
            if let topVC = self.getTopViewController() {
                let alert = UIAlertController(
                    title: "禁止截屏",
                    message: "当前页面不允许截屏或录屏。",
                    preferredStyle: .alert
                )
                alert.addAction(UIAlertAction(title: "确定", style: .default))
                topVC.present(alert, animated: true)
            }
        }

        // 3. 添加防录屏层（录制时黑屏，屏幕正常显示）
        addSecureScreenLayer()

        result(true)
    }

    /// 处理关闭屏幕保护
    func handleDisableScreenProtection(result: @escaping FlutterResult) {
        // 1. 移除监听
        if let observer = screenCaptureObserver {
            NotificationCenter.default.removeObserver(observer)
            screenCaptureObserver = nil
        }

        // 2. 移除防录屏层
        removeSecureScreenLayer()

        result(true)
    }

    /// 添加防录屏安全层
    private func addSecureScreenLayer() {
        guard Self.secureField == nil else { return }

        // 创建一个安全的 UITextField
        let field = UITextField()
        field.isSecureTextEntry = true
        field.backgroundColor = .clear
        field.isUserInteractionEnabled = false
        field.translatesAutoresizingMaskIntoConstraints = false

        if let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
            keyWindow.addSubview(field)
            keyWindow.layer.superlayer?.addSublayer(field.layer)
            field.layer.sublayers?.first?.addSublayer(keyWindow.layer)
        }

        Self.secureField = field
    }

    /// 移除安全层
    private func removeSecureScreenLayer() {
        Self.secureField?.removeFromSuperview()
        Self.secureField = nil
    }
    /// 获取当前顶层ViewController（用于弹窗）
    func getTopViewController() -> UIViewController? {
        var topVC = UIApplication.shared.keyWindow?.rootViewController
        while topVC?.presentedViewController != nil {
            topVC = topVC?.presentedViewController
        }
        return topVC
    }
    
}
